package com.joysuch.wwyt.api.sync.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.api.sync.SyncResponse;
import com.joysuch.wwyt.api.sync.bean.BaseEquipmentBean;
import com.joysuch.wwyt.api.sync.bean.BaseEquipmentListBean;
import com.joysuch.wwyt.api.sync.service.BaseSyncEquipmentService;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityCollection;
import com.joysuch.wwyt.bp.entity.BpProductionFacility;
import com.joysuch.wwyt.bp.entity.BpProductionFacilityType;
import com.joysuch.wwyt.bp.enums.DeviceFacilityTypes;
import com.joysuch.wwyt.bp.enums.ProductionFacilityStates;
import com.joysuch.wwyt.bp.repository.BpDeviceFacilityCollectionDao;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityDao;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityTypeDao;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.bp.service.BpProductionFacilityService;
import com.joysuch.wwyt.bp.service.BpProductionFacilityTypeService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
@Slf4j
public class BaseSyncEquipmentServiceImpl implements BaseSyncEquipmentService {

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BpProductionFacilityTypeService productionFacilityTypeService;

    @Autowired
    private BpProductionFacilityDao productionFacilityDao;

    @Autowired
    private BpProductionFacilityService productionFacilityService;

    @Autowired
    private RiskDistrictDao riskDistrictDao;



    @Autowired
    private BpDeviceFacilityCollectionDao deviceFacilityCollectionDao;


    @Autowired
    private BpProductionFacilityTypeDao productionFacilityTypeDao;





    /**
     *  同步每个公司的设备列表
     */

    @Override
    public void syncEquipment() {
        Set<String> bukrs = SyncConstants.unitCodeMap.keySet();
        for(String companyCode: bukrs){
            try {
                syncEquipmentByCompany(companyCode);
            }catch(Exception e){
                log.error("设备装置同步出错： companyCode={}",companyCode,e);
            }
        }

    }



    // 根据公司代码，获取设备列表同步更新到数据表
    @Override
     public ResultBean syncEquipmentByCompany(String companyCode) {
        String bukr = SyncConstants.unitCodeMap.get(companyCode);
        Long tenentId = 1L;
        BaseConfig equipConfig = baseConfigService.findConfig(tenentId,companyCode,SyncConstants.BASE_CONFIG_EQUIPMENT_LIST_URL);
        if(equipConfig != null && StringUtils.isNotEmpty(equipConfig.getValue())) {
            HttpHeaders header = new HttpHeaders();
            header.setContentType(MediaType.APPLICATION_JSON);
            //set body
            HttpEntity<String> requestBody = new HttpEntity<String>(bukr, header);
            Map<String, String> paraMap = new HashMap<>();
            paraMap.put("unitNo", bukr);
            log.info("设备列表同步Job：url={}, param={}", equipConfig.getValue(), paraMap);
            String url = equipConfig.getValue() + "?unitNo=" + bukr;
            SyncResponse response = restTemplate.postForObject(url, requestBody, SyncResponse.class, paraMap);
            if (response.getMsgcode().equals("0")) {
                if (response.getData() == null) {
                    log.info("设备列表同步Job： 获取数据列表为空,共同步0条记录， URL={}", equipConfig.getValue());
                    return ResultBean.success("设备列表同步完成：<br> 获取数据列表为空,共同步0条记录；");
                }
                String data = JSONObject.toJSONString(response.getData());

                JSONObject content = JSONObject.parseObject(data);
                Integer count = processEquipmentList(content.getString("content"), companyCode);
                return ResultBean.success("设备列表同步完成：<br> 共同步{}条记录；", count.toString());
            } else {
                log.error("设备列表同步Job： 获取数据出现异常： {}", response);
                return ResultBean.success("设备列表同步完成：<br> 获取数据出现异常：{}", response.getMsg());
            }
        }
            log.error("设备列表同步完成： 设备同步接口未配置 {} ",SyncConstants.BASE_CONFIG_EQUIPMENT_LIST_URL  );
            return ResultBean.success("设备列表同步完成：<br> 设备同步接口未配置");

        }



    /**
     * 新增/更新 设备列表信息
     * @param content
     */
   private Integer processEquipmentList(String content, String companyCode) {
      //  private void processEquipmentList(List<BaseEquipmentBean> list, String companyCode) {
       List<BpProductionFacility> updateList = new ArrayList<>();
        if(content != null){
            List<BaseEquipmentBean> list = JSONArray.parseArray(content,BaseEquipmentBean.class );
            log.info("....company={} ,list:{} ....", companyCode, list.size());
            List<BpProductionFacilityType> typeList = productionFacilityTypeService.findList(companyCode);
            Map<String,BpProductionFacilityType> typeMap = new HashMap<>();
            if(typeList != null){
                for(BpProductionFacilityType t: typeList){
                    typeMap.put(t.getName(), t);
                }
            }

            List<String> codeList = new ArrayList<>();
            Map<Long, BpProductionFacilityType> typeUpdateMap = new HashMap<>();
            List<BpDeviceFacilityCollection> deviceList = new ArrayList<>();
            //保养周期
            Integer  maintainPeriodDays = null;
            int maintainUnit =0;
            //通过配置，控制同步的设备类型：不在配置列表的类型不做修改
            BaseConfig equipTypeConfig =  baseConfigService.findConfig(SyncConstants.TENENT_ID_DEFAULT, companyCode,SyncConstants.BASE_CONFIG_EQUIPMENT_TYPE_LIST);
            List<String> equipTypeList = null;
            if(equipTypeConfig != null && StringUtils.isNotEmpty(equipTypeConfig.getValue())){
                equipTypeList = new ArrayList<>();
                equipTypeList = Arrays.asList(equipTypeConfig.getValue().split(";"));
            }

            for(BaseEquipmentBean equip: list){

                // 不在配置列表的类型不做同步，直接忽略
                if(equipTypeList != null && StringUtils.isNotEmpty(equip.getDeviceTypeName())){
                    if(!equipTypeList.contains(equip.getDeviceTypeName().trim())){
                        continue;
                    }
                }

                BpProductionFacility bpf = null;
                //设备类型
                BpProductionFacilityType type = typeMap.get(equip.getDeviceTypeName());
                if(typeMap.containsKey(equip.getDeviceTypeName())){
                    type.setNumber(type.getNumber() +1);
                    bpf = productionFacilityService.findByCode(equip.getCode(), companyCode) ;
                    typeUpdateMap.put(type.getId(), type);
                }else{
                    // 类型不存在则创建新类型
                    type = createNewType(equip.getDeviceTypeName(),companyCode);
                }
                //更新类型数量
                typeMap.put(equip.getDeviceTypeName(), type);

                if(bpf == null){
                    bpf = new BpProductionFacility();
                    bpf.setCode(equip.getCode());
                    bpf.setOrgCode(companyCode);
                    bpf.setTenentId(1L);
                    bpf.setDeleteFlag("0");
                }
                bpf.setType(type.getId());
                bpf.setName(equip.getName());
                bpf.setRefId(equip.getRefId());
                bpf.setRefUrl(equip.getRefUrl());
                bpf.setValidityDate(equip.getValidity_date());
                bpf.setEquipmentModel(equip.getEquip_model());
               RiskDistrict risk=  riskDistrictDao.findByCodeAndCompanyCode(equip.getLocat_no(), companyCode);
               if(risk != null){
                   bpf.setRiskDistrictId(risk.getId());
               }

                if(equip.getSafe_status() != null){
                    bpf.setSafeStatus("Y".equalsIgnoreCase(equip.getSafe_status())? "是":"否");
                }

                if(equip.getState()== null  || 2 == equip.getState()){
                    bpf.setState(ProductionFacilityStates.RUNNING.getId());
                }else if(5 ==equip.getState()){
                    bpf.setState(ProductionFacilityStates.REPAIRING.getId());
                }else{
                    bpf.setState(ProductionFacilityStates.STOPED.getId());
                }
                //保养周期 计算
                if(equip.getCal_cycle() != null && equip.getCycle_unit() != null){

                    if("Y".equalsIgnoreCase(equip.getCycle_unit())){
                        maintainUnit = 365;
                    }else if("M".equalsIgnoreCase(equip.getCycle_unit())){
                        maintainUnit = 30;
                    }if("D".equalsIgnoreCase(equip.getCycle_unit())){
                        maintainUnit = 1;
                    }
                    try{
                        maintainPeriodDays= Integer.parseInt(equip.getCal_cycle()) * maintainUnit;
                        bpf.setMaintainPeriodDays(maintainPeriodDays);
                    }catch (Exception e){
                      log.error("设备装置周期计算类型转换异常",e);
                    }

                }
                //过滤code 重复的脏数据
                if(!codeList.contains(bpf.getCode())){
                    updateList.add(bpf);
                    codeList.add(bpf.getCode());

                    //更新设备列表
                    BpDeviceFacilityCollection device = addOrUpdateDeviceFacilityCollection(bpf, type.getName());
                    deviceList.add(device);
                }


                if(updateList.size() >100){
                    log.info(".....update list {} ， company={}", updateList.size(),companyCode);
                    productionFacilityDao.saveAll(updateList);
                    updateList= new ArrayList<>();
                }
                if(deviceList.size() >100){
                    deviceFacilityCollectionDao.saveAll(deviceList);
                    deviceList = new ArrayList<>();
                }
            }

            if(updateList.size() >0){
                productionFacilityDao.saveAll(updateList);
                log.info(".....update list {} ， company={}", updateList.size(),companyCode);
            }
            if(deviceList.size() >0){
                deviceFacilityCollectionDao.saveAll(deviceList);
            }

            //更新类型绑定的设备数量
            if(typeUpdateMap.size() >0){
                List<BpProductionFacilityType> typeUpdateList = new ArrayList<>();
                Set<Long> keys= typeUpdateMap.keySet();
                for(Long key: keys){
                    typeUpdateList.add(typeUpdateMap.get(key));
                }
               productionFacilityTypeDao.saveAll(typeUpdateList);
            }

        }
        return updateList.size();

    }

    private BpProductionFacilityType createNewType(String typeName, String companyCode){
        BpProductionFacilityType type = new BpProductionFacilityType();
        type.setName(typeName);
        type.setNumber(1);
        type.setOrgCode(companyCode);
        type.setDeleteFlag("0");
        type.setTenentId(1L);
        type.setParentId(0L);
        return productionFacilityTypeDao.save(type);
    }



    private  BpDeviceFacilityCollection addOrUpdateDeviceFacilityCollection(BpProductionFacility bpf, String typeName){
        BpDeviceFacilityCollection device = deviceFacilityCollectionDao.findFirstByDeviceTypeNameAndDeviceId(DeviceFacilityTypes.SHENG_CHAN_ZHUANG_ZHI.getName(), bpf.getId());
        if (device == null) {
            device = new BpDeviceFacilityCollection();
        }
        device.setCode(bpf.getCode());
        device.setName(bpf.getName());
        device.setDeviceId(bpf.getId());
        device.setDeviceTypeName(DeviceFacilityTypes.SHENG_CHAN_ZHUANG_ZHI.getName());
        device.setDeviceTypeId(bpf.getType());
        device.setSubType(typeName);
        device.setTenentId(1L);
        device.setOrgCode(bpf.getOrgCode());
        if(2 == bpf.getState()||5 == bpf.getState()||6 == bpf.getState()){
            device.setDeleteFlag("0");
        }else{
            device.setDeleteFlag("1");
        }
         return device;
    }



    private List<BaseEquipmentBean> getTestData(){
        BaseEquipmentListBean listBean = new BaseEquipmentListBean();
        List<BaseEquipmentBean> list = new ArrayList<>();
        BaseEquipmentBean bean = new BaseEquipmentBean();
        bean.setCode("T10001");
        bean.setDeviceTypeName("设备类型同步-1");
        bean.setName("蒸馏器");
        bean.setRefId("123");
        bean.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=431");
        bean.setState(0);

        BaseEquipmentBean bean2 = new BaseEquipmentBean();
        bean2.setCode("T10002");
        bean2.setDeviceTypeName("设备类型同步-2");
        bean2.setName("蒸馏器2");
        bean2.setRefId("1232");
        bean2.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean2.setState(2);

        BaseEquipmentBean bean3 = new BaseEquipmentBean();
        bean3.setCode("T10003");
        bean3.setDeviceTypeName("设备类型同步-3");
        bean3.setName("蒸馏器3");
        bean3.setRefId("1234");
        bean3.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean3.setState(3);

        BaseEquipmentBean bean4 = new BaseEquipmentBean();
        bean4.setCode("T10004");
        bean4.setDeviceTypeName("设备类型同步-4");
        bean4.setName("蒸馏器4");
        bean4.setRefId("1232");
        bean4.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean4.setState(4);

        BaseEquipmentBean bean5 = new BaseEquipmentBean();
        bean5.setCode("T10005");
        bean5.setDeviceTypeName("设备类型同步-5");
        bean5.setName("蒸馏器5");
        bean5.setRefId("1234");
        bean5.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean5.setState(5);

        BaseEquipmentBean bean6 = new BaseEquipmentBean();
        bean6.setCode("T10006");
        bean6.setDeviceTypeName("设备类型同步-5");
        bean6.setName("蒸馏器6");
        bean6.setRefId("1234");
        bean6.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean6.setState(6);


        BaseEquipmentBean bean7 = new BaseEquipmentBean();
        bean7.setCode("T10007");
        bean7.setDeviceTypeName("设备类型同步-5");
        bean7.setName("蒸馏器7");
        bean7.setRefId("1234");
        bean7.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean7.setState(7);


        BaseEquipmentBean bean8 = new BaseEquipmentBean();
        bean8.setCode("T10008");
        bean8.setDeviceTypeName("设备类型同步-8");
        bean8.setName("蒸馏器8");
        bean8.setRefId("1234");
        bean8.setRefUrl("http://wwtest.joysuch.com/bp/production/getById?id=428");
        bean8.setState(8);


        list.add(bean);
        list.add(bean2);
        list.add(bean3);
        list.add(bean4);
        list.add(bean5);
        list.add(bean6);
        list.add(bean7);
        list.add(bean8);
        listBean.setContent(list);
        return list;

//        SyncResponse response = new SyncResponse();
//        response.setMsg("success");
//        response.setMsgcode("0");
//        response.setData(JSONObject.toJSONString(listBean));
//
//        return response;

    }
    }

